package com.xunmeng.chapter3;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

public class WriteServer {
    public static void main(String[] args) throws IOException {
        // 创建服务端程序
        ServerSocketChannel scc=ServerSocketChannel.open();
        scc.configureBlocking(false);// 关闭阻塞
        // 绑定服务地址
        scc.bind(new InetSocketAddress(8080));
        // 创建Selector对象
        Selector selector = Selector.open();
        SelectionKey sccKey = scc.register(selector, 0, null);
        sccKey.interestOps(SelectionKey.OP_ACCEPT);

        // 接收事件
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()){
                    //这个是客户端连接事件
                    ServerSocketChannel channel= (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();// 获取连接
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, 0, null);
                    sckey.interestOps(SelectionKey.OP_READ);
                    // 建立后向服务端发送消息
                    // 创建消息
                    StringBuilder sb=new StringBuilder();
                    for(int i=0;i<500000000;i++){
                        sb.append("a");
                    }
                    ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(sb.toString());
                    int write = sc.write(byteBuffer);
                    System.out.println(write);
                    if (byteBuffer.hasRemaining()){
                        // 说明还有数据，那么放到下一次读取
                        sckey.interestOps(sckey.interestOps()+SelectionKey.OP_WRITE);
                        sckey.attach(byteBuffer);
                    }
                }else if (key.isWritable()){
                    // 写数据
                    ByteBuffer buffer= (ByteBuffer) key.attachment();
                    SocketChannel sc= (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    if(!buffer.hasRemaining()){
                        key.interestOps(key.interestOps()-SelectionKey.OP_WRITE);
                        key.attach(null);
                    }
                }
            }
        }

    }
}
